<template>
	<div class="padding-across-10" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
		<headerOpreate :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
		<div style="width: 100%">
			<div style="float: left;padding-bottom: 3px">
				<span style="font-size: 13px;font-weight: bold">检索字段</span>
				<el-select style="margin-top: 2px;width: 90px" size="small" v-model="findType" placeholder="检索字段">
					<el-option label="昵称" :value="0"></el-option>
					<el-option label="用户名" :value="1"></el-option>
				</el-select>
				<span style="font-size: 13px;font-weight: bold">关键字</span>
				<el-input style="width: 160px" v-model="keyWord" size="small" placeholder="查询关键字">
					<el-button id="searchUserData" slot="append" icon="search" @click="getDatas"></el-button>
				</el-input>
			</div>
			<div class="block" style="text-align:right;float: right;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
		</div>
		<el-table border style="width: 100%;" @selection-change="handleSelectionChange" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" align="center" type="selection"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="用户名" align="center" prop="uid"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="卡号" align="center" prop="card"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="昵称" align="center" prop="nickname"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="权限" align="center" prop="role"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="优先级" align="center" width="200">
				<template slot-scope="scope">
					<el-radio-group v-model="scope.row.priority">
						<el-radio :label="3">低</el-radio>
						<el-radio :label="2">中</el-radio>
						<el-radio :label="1">高</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" :label="$t('message.operation')" align="center">
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="editUser(scope.row)"><i class="el-icon-edit el-icon--left"></i>编辑</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="block" style="text-align:right;margin-bottom:60px;padding-top: 2px">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
			</el-pagination>
		</div>
		<!-- 创建用户 -->
		<el-dialog title="注册用户" v-model="createUserDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="createForm" :model="createForm" :rules="createRules" label-width="100px">
				<el-form-item label="用户名" prop="uid">
					<el-input v-model="createForm.uid" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="卡号" prop="card">
					<el-input v-model="createForm.card" style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="昵称" prop="nickname">
					<el-input v-model="createForm.nickname" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="createForm.password" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="checkPass">
					<el-input type="password" v-model="createForm.checkPass" required style="max-width:480px"></el-input>
				</el-form-item>
				<el-form-item label="用户权限" prop="role">
					<el-select style="width: 100%" v-model="createForm.role" placeholder="请选择用户权限" required>
						<el-option v-for="item in roleDatas" :key="item.KeyId" :label="item.Name" :value="item.KeyId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="优先级" prop="priority" required>
					<el-radio-group v-model="createForm.priority">
						<el-radio :label="3">低</el-radio>
						<el-radio :label="2">中</el-radio>
						<el-radio :label="1">高</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="createUserDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmCreateUser('createForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!--导入excel-->
		<el-dialog title="导入用户Excel" v-model="importExcelDialog" :class="[dialog-small-width]">
			<div style="width:360px;margin:auto">
				<uploadSection v-if="importExcelDialog" ref="importSection" upload-url="/Api/User/File/ExcelImportUser" accept-types="xls,xlsx" v-on:uploadComplete="uploadComplete">
				</uploadSection>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import { GloabFun, HttpServer } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'
	import uploadSection from '../../../../components/import'
	const JSEncrypt = require("jsencrypt"); // 引入模块
	const encrypt = new JSEncrypt.JSEncrypt(); // 实例化加密对象
	let id = 1000;
	export default {
		components: {
			headerOpreate,
			uploadSection
		},
		data() {
			//回车触发查询按钮
			document.onkeydown = function(event) {
				var e = event || window.event;
				if(e && e.keyCode == 13) { //回车键的键值为13
					$("#searchUserData").click();
				}
			};
			//用户名正则表达式：由数字和字母组成
			var create_checkUid = (rule, value, callback) => {
				if(this.createForm.uid === '') {
					callback(new Error('用户名不能为空'));
				} else if(!((/^[0-9a-zA-Z_]{1,}$/).test(this.createForm.uid))) {
					callback(new Error('用户名由数字、字母或下划线组成'));
				} else {
					callback();
				}
			};
			//密码验证
			var create_checkPassword = (rule, value, callback) => {
				if(this.createForm.password === '') {
					callback(new Error('密码不能为空'));
				} else if(!((/^[0-9a-zA-Z_]{6,20}$/).test(this.createForm.password))) {
					callback(new Error('密码必须为6-20位数字、字母或下划线'));
				} else {
					callback();
				}
			}
			//再次输入密码验证
			var create_checkPass = (rule, value, callback) => {
				if(this.createForm.checkPass === '') {
					callback(new Error('请再次输入密码'));
				} else if(this.createForm.checkPass !== this.createForm.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				isReload: false,
				importExcelDialog: false,
				findType: 0,
				keyWord: '',
				roleDatas: [], //角色下拉菜单
				publicKey: '',
				loading: false,
				createUserDialog: false,
				changeNickNameDialog: false,
				defaultProps: {
					children: 'Children',
					label: 'Name',
					id: 'Id'
				},
				data: [],
				dynamicTags: [],
				inputVisible: false,
				inputValue: '',
				tableData: [],
				multipleSelection: [],
				roleList: [],
				setRole: '',
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				opreateDatas: [{
						show: true,
						size: "small",
						type: 'primary',
						icon: 'el-icon-eleg-icon_refresh el-icon--left',
						name: this.$t("message.refresh"),
						action: 'reloadDatas'
					},
					{
						show: true,
						size: "small",
						type: "primary",
						icon: "el-icon-plus el-icon--left",
						name: "添加",
						action: "createUser"
					},
					{
						show: true,
						size: 'small',
						type: 'primary',
						icon: 'el-icon-eleg-icon_lock_alt el-icon--left',
						name: '重置密码',
						action: 'resetPassword'
					},
					{
						show: true,
						size: "small",
						type: "primary",
						icon: "el-icon-eleg-icon_folder_upload el-icon--left",
						name: "导入表格",
						action: "showExcelDialog"
					},
					{
						show: true,
						size: "small",
						type: "primary",
						icon: "el-icon-document el-icon--left",
						name: "模板下载",
						action: "excelDownload"
					},
					{
						show: true,
						size: "small",
						type: "danger",
						icon: "el-icon-delete2 el-icon--left",
						name: "删除",
						action: "deleteMultiple"
					}
				],
				createForm: {
					card: '',
					uid: '',
					nickname: '',
					password: '',
					checkPass: '',
					email: '',
					phone: '',
					securitycode: '',
					role: 0,
					priority: 3
				},
				createRules: {
					uid: [{
						validator: create_checkUid,
						required: true,
						trigger: 'blur'
					}],
					nickname: [{
						required: true,
						message: "昵称不能为空",
						trigger: 'blur'
					}],
					password: [{
						validator: create_checkPassword,
						required: true,
						trigger: 'blur'
					}],
					checkPass: [{
						validator: create_checkPass,
						required: true,
						trigger: 'blur'
					}]
				},
			}
		},
		props: {
			templateObj: {
				type: Object,
				default: {}
			}
		},
		methods: {
			excelDownload() {
				window.open(localHost + '/Api/User/File/Download/ExcelFile?uid=' + GloabFun.getUid() + '&token=' + GloabFun.getToken() + '&filetype=3')
			},
			uploadComplete() {
				this.$notify({
					title: '成功',
					message: this.$t('message.uploadSuccess'),
					type: 'success',
					duration: 2500
				});
			},
			showExcelDialog() {
				this.importExcelDialog = true;
			},
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDatas();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.getDatas();
			},
			//公钥格式
			trim(str, is_global) {
				var result;
				result = str.replace(/(^\s+)|(\s+$)/g, "");
				if(is_global.toLowerCase() == "g") {
					result = result.replace(/\s/g, "");
				}
				return result;
			},
			getUserRoles() {
				HttpServer.httpPost.call(this, '/Api/Role/List', {
					ids: "",
					size: 0,
					page: 0,
					filter: '',
					UserId: parseInt(GloabFun.getKeyId())
				}, function(response) {}, function(response) {
					if(response.data.code === 0) {
						this.createForm.role = response.data.data[0].KeyId;
						this.roleDatas = response.data.data;
					}
				});
			},
			//打开新建用户弹窗
			createUser() {
				this.createUserDialog = true;
				this.getUserRoles();
				//获取公钥
				HttpServer.httpGet.call(this, "/Api/User/LoginKey/Js", function(response) {}, function(response) {
					this.publicKey = this.trim(response.data.key, "g")
				});
			},
			//确定创建用户
			confirmCreateUser(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						encrypt.setPublicKey(this.publicKey);
						var param = {
							createduid: this.createForm.uid,
							password: encrypt.encrypt(this.createForm.password),
							nickname: this.createForm.nickname,
							phone: this.createForm.phone,
							email: this.createForm.email,
							securitycode: this.createForm.securitycode,
							roles: '',
							roleid: this.createForm.role,
							priority: this.createForm.priority,
							card: this.createForm.card,
							m: 1
						}
						HttpServer.httpPost.call(this, '/Api/User/Create', param, function(response) {}, function(response) {
							// console.log('注册用户', response);
							if(response.data.code === 0) {
								this.getDatas();
								this.createUserDialog = false;
								this.createForm = {
									uid: '',
									nickname: '',
									password: '',
									checkPass: '',
									email: '',
									phone: '',
									securitycode: '',
									role: 0
								};
								this.$notify({
									title: '成功',
									message: '用户注册成功',
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			formateSelection() {
				var result = [],
					array = this.multipleSelection;
				for(var i = 0; i < array.length; i++) {
					result.push(array[i].keyid);
				}
				return result;
			},
			//重置密码
			resetPassword(row) {
				if(this.formateSelection().length > 0) {
					this.$confirm('此操作将重置用户密码，是否继续？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						HttpServer.httpPost.call(this, '/Api/User/ResetPassword', {
							keyid: this.formateSelection()
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.getDatas();
								this.$notify({
									title: '成功',
									message: '密码重置成功',
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.cancleOperation'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择要批量操作的项',
						type: 'warning',
						duration: 2500
					});
				}
			},
			//批量删除用户
			deleteMultiple() {
				if(this.formateSelection().length > 0) {
					this.$confirm('此操作将删除用户信息，是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						HttpServer.httpPost.call(this, '/api/user/delete', {
							keyid: this.formateSelection()
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.getDatas();
								this.$notify({
									title: '成功',
									message: this.$t('message.bulkDeleteSuccess'),
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.cancleOperation'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: this.$t('message.selectBulkDeleteWarning'),
						type: 'warning',
						duration: 2500
					});
				}
			},
			//打开用户编辑弹窗
			editUser(row) {
				row.pageSize = this.pageSize;
				row.currentPage = this.currentPage;
				this.$emit('changeView', 'Edit', row);
			},

			//刷新
			reloadDatas() {
				this.isReload = true;
				this.getDatas();
			},
			getDatas() {
				this.loading = true;
				HttpServer.httpPost.call(this, '/Api/User/info', {
					loginname: this.findType === 1 ? this.keyWord : '',
					pagesize: this.pageSize,
					index: this.currentPage,
					nickname: this.findType === 0 ? this.keyWord : ''
				}, function(response) {}, function(response) {
					this.loading = false;
					if(response.data.code === 0) {
						this.tableData = response.data.info;
						this.totalSize = response.data.totalcount;
						if(this.isReload) {
							this.$notify({
								title: '成功',
								message: this.$t('message.refreshSuccess'),
								type: 'success',
								duration: 2500
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
					this.isReload = false;
				});
			}
		},
		created() {
			if(this.templateObj.pageSize && this.templateObj.pageSize != 0) {
				this.pageSize = this.templateObj.pageSize;
				this.currentPage = this.templateObj.currentPage;
			}
			this.getDatas();
		}
	}
</script>
<style scoped lang="less">
	.name {
		color: #20a0ff;
	}
	
	.edit-mission {
		padding-top: 50px;
		.el-dialog__header {
			background-color: #000;
		}
		.el-dialog__body {
			position: relative;
		}
		.clearfloat {
			height: 100px;
			max-height: 150px;
		}
	}
</style>